using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

namespace UnifiedFileDialog
{
    // 存储选择结果的数据类
    public class FileSystemSelection
    {
        public List<string> Files { get; } = new List<string>();
        public List<string> Directories { get; } = new List<string>();
    }

    // 主对话框类
    public class UnifiedFileDialog : Form
    {
        private TreeView tvNavigation;
        private ListView lvItems;
        private TextBox txtPath;
        private Button btnUp;
        private Button btnOK;
        private Button btnCancel;
        private ComboBox cbFilter;
        private CheckBox chkAllowFiles;
        private CheckBox chkAllowDirs;
        
        // 配置属性
        public string Filter { get; set; } = "所有文件 (*.*)|*.*";
        public bool Multiselect { get; set; } = true;
        public string InitialDirectory { get; set; }
        
        // 选择结果
        public FileSystemSelection Selection { get; private set; } = new FileSystemSelection();

        public UnifiedFileDialog()
        {
            InitializeComponents();
            LoadFileSystem();
            UpdateFilterComboBox();
        }

        private void InitializeComponents()
        {
            // 窗体基本设置
            Text = "选择文件或目录";
            Size = new Size(900, 600);
            StartPosition = FormStartPosition.CenterScreen;
            FormBorderStyle = FormBorderStyle.FixedDialog;
            MaximizeBox = false;

            // 创建导航面板
            var pnlNavigation = new Panel { Dock = DockStyle.Left, Width = 250 };
            
            // 目录树视图
            tvNavigation = new TreeView {
                Dock = DockStyle.Fill,
                ShowLines = true,
                ShowPlusMinus = true,
                ImageList = new ImageList()
            };
            tvNavigation.ImageList.Images.Add("folder", SystemIcons.Folder.ToBitmap());
            tvNavigation.ImageList.Images.Add("drive", SystemIcons.MyComputer.ToBitmap());
            tvNavigation.AfterSelect += TvNavigation_AfterSelect;

            pnlNavigation.Controls.Add(tvNavigation);

            // 创建主面板
            var pnlMain = new Panel { Dock = DockStyle.Fill };

            // 路径导航栏
            var pnlPath = new Panel { Dock = DockStyle.Top, Height = 30 };
            
            btnUp = new Button { Text = "↑", Dock = DockStyle.Left, Width = 30 };
            btnUp.Click += BtnUp_Click;
            
            txtPath = new TextBox { Dock = DockStyle.Fill, ReadOnly = true };
            
            pnlPath.Controls.Add(txtPath);
            pnlPath.Controls.Add(btnUp);

            // 选项面板
            var pnlOptions = new Panel { Dock = DockStyle.Top, Height = 30 };
            
            chkAllowFiles = new CheckBox { Text = "允许选择文件", Checked = true, Dock = DockStyle.Left, Width = 120 };
            chkAllowDirs = new CheckBox { Text = "允许选择目录", Checked = true, Dock = DockStyle.Left, Width = 120 };
            
            cbFilter = new ComboBox { Dock = DockStyle.Right, Width = 200, DropDownStyle = ComboBoxStyle.DropDownList };
            cbFilter.SelectedIndexChanged += CbFilter_SelectedIndexChanged;
            
            pnlOptions.Controls.Add(chkAllowFiles);
            pnlOptions.Controls.Add(chkAllowDirs);
            pnlOptions.Controls.Add(cbFilter);

            // 文件列表视图
            lvItems = new ListView {
                Dock = DockStyle.Fill,
                View = View.Details,
                FullRowSelect = true,
                MultiSelect = Multiselect,
                GridLines = true,
                ImageList = new ImageList()
            };
            lvItems.ImageList.Images.Add("folder", SystemIcons.Folder.ToBitmap());
            lvItems.ImageList.Images.Add("file", SystemIcons.File.ToBitmap());
            lvItems.Columns.Add("名称", 250);
            lvItems.Columns.Add("类型", 150);
            lvItems.Columns.Add("大小", 100, HorizontalAlignment.Right);
            lvItems.Columns.Add("修改日期", 150);
            lvItems.DoubleClick += LvItems_DoubleClick;

            // 按钮面板
            var pnlButtons = new Panel { Dock = DockStyle.Bottom, Height = 40 };
            
            btnOK = new Button { Text = "确定", DialogResult = DialogResult.OK, Width = 75, Location = new Point(700, 5) };
            btnCancel = new Button { Text = "取消", DialogResult = DialogResult.Cancel, Width = 75, Location = new Point(780, 5) };
            
            pnlButtons.Controls.Add(btnOK);
            pnlButtons.Controls.Add(btnCancel);

            // 组装主面板
            pnlMain.Controls.Add(pnlButtons);
            pnlMain.Controls.Add(lvItems);
            pnlMain.Controls.Add(pnlOptions);
            pnlMain.Controls.Add(pnlPath);

            // 组装窗体
            Controls.Add(pnlMain);
            Controls.Add(pnlNavigation);

            // 关闭时收集选择结果
            FormClosing += (s, e) => {
                if (DialogResult == DialogResult.OK) {
                    CollectSelection();
                }
            };
        }

        // 加载文件系统
        private void LoadFileSystem()
        {
            try
            {
                // 加载所有驱动器
                foreach (var drive in DriveInfo.GetDrives())
                {
                    if (drive.IsReady)
                    {
                        var node = new TreeNode(drive.Name) {
                            Tag = drive.RootDirectory.FullName,
                            ImageKey = "drive",
                            SelectedImageKey = "drive"
                        };
                        tvNavigation.Nodes.Add(node);
                        AddSubdirectories(node); // 添加一级子目录
                    }
                }

                // 设置初始目录
                if (!string.IsNullOrEmpty(InitialDirectory) && Directory.Exists(InitialDirectory))
                {
                    NavigateToDirectory(InitialDirectory);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载文件系统失败: {ex.Message}", "错误");
            }
        }

        // 添加子目录
        private void AddSubdirectories(TreeNode parentNode)
        {
            try
            {
                string path = parentNode.Tag.ToString();
                foreach (var dir in Directory.GetDirectories(path))
                {
                    var node = new TreeNode(Path.GetFileName(dir)) {
                        Tag = dir,
                        ImageKey = "folder",
                        SelectedImageKey = "folder"
                    };
                    parentNode.Nodes.Add(node);
                    node.Nodes.Add(new TreeNode()); // 占位符，用于延迟加载
                }
            }
            catch { /* 忽略无权限访问的目录 */ }
        }

        // 导航到指定目录
        private void NavigateToDirectory(string path)
        {
            if (!Directory.Exists(path)) return;

            txtPath.Text = path;
            LoadDirectoryItems(path);
            
            // 展开树视图中对应的节点
            ExpandTreeNodeForPath(path);
        }

        // 展开对应路径的树节点
        private void ExpandTreeNodeForPath(string path)
        {
            // 简化实现，完整实现需要递归查找路径对应的节点
            foreach (TreeNode node in tvNavigation.Nodes)
            {
                if (path.StartsWith(node.Tag.ToString()))
                {
                    tvNavigation.SelectedNode = node;
                    node.Expand();
                    break;
                }
            }
        }

        // 加载目录中的项目
        private void LoadDirectoryItems(string path)
        {
            lvItems.Items.Clear();
            
            try
            {
                // 添加目录
                if (chkAllowDirs.Checked)
                {
                    foreach (var dir in Directory.GetDirectories(path))
                    {
                        var dirInfo = new DirectoryInfo(dir);
                        var item = new ListViewItem(Path.GetFileName(dir)) {
                            ImageKey = "folder",
                            Tag = dir
                        };
                        item.SubItems.Add("文件夹");
                        item.SubItems.Add("");
                        item.SubItems.Add(dirInfo.LastWriteTime.ToString());
                        lvItems.Items.Add(item);
                    }
                }

                // 添加文件（应用筛选器）
                if (chkAllowFiles.Checked)
                {
                    foreach (var file in GetFilteredFiles(path))
                    {
                        var fileInfo = new FileInfo(file);
                        var item = new ListViewItem(Path.GetFileName(file)) {
                            ImageKey = "file",
                            Tag = file
                        };
                        item.SubItems.Add(Path.GetExtension(file).ToUpper() + " 文件");
                        item.SubItems.Add(fileInfo.Length.ToString("N0") + " 字节");
                        item.SubItems.Add(fileInfo.LastWriteTime.ToString());
                        lvItems.Items.Add(item);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"无法加载目录内容: {ex.Message}", "错误");
            }
        }

        // 根据筛选器获取文件
        private string[] GetFilteredFiles(string path)
        {
            var filterPatterns = GetCurrentFilterPatterns();
            var files = new HashSet<string>(); // 使用HashSet避免重复文件

            foreach (var pattern in filterPatterns)
            {
                try
                {
                    foreach (var file in Directory.GetFiles(path, pattern))
                    {
                        files.Add(file);
                    }
                }
                catch { /* 忽略错误 */ }
            }

            return new List<string>(files).ToArray();
        }

        // 解析当前筛选器模式
        private string[] GetCurrentFilterPatterns()
        {
            if (string.IsNullOrEmpty(Filter))
                return new[] { "*.*" };

            var filterParts = Filter.Split('|');
            if (filterParts.Length > cbFilter.SelectedIndex * 2 + 1)
            {
                return filterParts[cbFilter.SelectedIndex * 2 + 1].Split(';');
            }

            return new[] { "*.*" };
        }

        // 更新筛选器下拉框
        private void UpdateFilterComboBox()
        {
            if (string.IsNullOrEmpty(Filter))
                return;

            var filterParts = Filter.Split('|');
            for (int i = 0; i < filterParts.Length; i += 2)
            {
                cbFilter.Items.Add(filterParts[i]);
            }
            cbFilter.SelectedIndex = 0;
        }

        // 收集选择结果
        private void CollectSelection()
        {
            Selection.Files.Clear();
            Selection.Directories.Clear();

            foreach (ListViewItem item in lvItems.SelectedItems)
            {
                if (item.Tag is string path)
                {
                    if (Directory.Exists(path))
                    {
                        Selection.Directories.Add(path);
                    }
                    else if (File.Exists(path))
                    {
                        Selection.Files.Add(path);
                    }
                }
            }
        }

        // 事件处理：树视图选择变更
        private void TvNavigation_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Tag is string path && Directory.Exists(path))
            {
                NavigateToDirectory(path);
            }
        }

        // 事件处理：列表项双击
        private void LvItems_DoubleClick(object sender, EventArgs e)
        {
            if (lvItems.SelectedItems.Count > 0)
            {
                var selectedPath = lvItems.SelectedItems[0].Tag.ToString();
                if (Directory.Exists(selectedPath))
                {
                    // 如果是目录，则导航进入
                    NavigateToDirectory(selectedPath);
                }
                else if (File.Exists(selectedPath) && !Multiselect)
                {
                    // 如果是文件且不允许多选，则直接确定
                    DialogResult = DialogResult.OK;
                }
            }
        }

        // 事件处理：上一级按钮
        private void BtnUp_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtPath.Text))
            {
                var parentDir = Directory.GetParent(txtPath.Text);
                if (parentDir != null)
                {
                    NavigateToDirectory(parentDir.FullName);
                }
            }
        }

        // 事件处理：筛选器变更
        private void CbFilter_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtPath.Text))
            {
                LoadDirectoryItems(txtPath.Text);
            }
        }

        // 显示对话框的静态方法
        public static FileSystemSelection ShowDialog()
        {
            using (var dialog = new UnifiedFileDialog())
            {
                return dialog.ShowDialog() == DialogResult.OK ? dialog.Selection : new FileSystemSelection();
            }
        }
    }

    // 使用示例
    public class DemoForm : Form
    {
        public DemoForm()
        {
            var btnSelect = new Button {
                Text = "选择文件和目录",
                Location = new Point(50, 50),
                Size = new Size(150, 30)
            };
            btnSelect.Click += (s, e) => {
                var result = UnifiedFileDialog.ShowDialog();
                
                string message = $"选择结果:\n\n";
                message += $"文件 ({result.Files.Count}):\n{string.Join("\n", result.Files)}\n\n";
                message += $"目录 ({result.Directories.Count}):\n{string.Join("\n", result.Directories)}";
                
                MessageBox.Show(message, "选择完成");
            };
            
            Controls.Add(btnSelect);
            Size = new Size(300, 200);
        }
    }
}
